package com.demo.forum.services.impl;

import com.demo.forum.common.Result;
import com.demo.forum.common.ResultCode;
import com.demo.forum.dao.ArticleReplyMapper;
import com.demo.forum.model.ArticleReply;
import com.demo.forum.model.exception.ApplicationException;
import com.demo.forum.services.IArticleReplyService;
import com.demo.forum.utils.StringUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;

@Service
@Slf4j

public class ArticleReplyServiceImpl implements IArticleReplyService {
    @Autowired
    private ArticleReplyMapper articleReplyMapper;
    @Autowired
    private ArticleServiceImpl articleService;
    @Override
    public void create(ArticleReply articleReply) {
        if(articleReply == null || articleReply.getArticleId() == null
            || articleReply.getPostUserId() == null
            || StringUtil.isEmpty(articleReply.getContent())){
            log.warn(ResultCode.FAILED_PARAMS_VALIDATE.toString());
            throw  new ApplicationException(Result.failed(ResultCode.FAILED_PARAMS_VALIDATE));
        }
        articleReply.setDeleteState((byte) 0);
        articleReply.setState((byte) 0);
        articleReply.setLikeCount(0);
        Date date = new Date();
        articleReply.setCreateTime(date);
        articleReply.setUpdateTime(date);
        articleReply.setReplyId(null);
        articleReply.setReplyUserId(null);
        int row = articleReplyMapper.insertSelective(articleReply);
        if(row != 1){
            log.warn(ResultCode.ERROR_SERVICES.toString());
            // 抛出异常
            throw new ApplicationException(Result.failed(ResultCode.ERROR_SERVICES));
        }
        articleService.addOneReplyCountById(articleReply.getArticleId());
        log.info("回复帖子成功" + " , article id = " + articleReply.getArticleId()
                +", user id =" + articleReply.getPostUserId());

    }

    @Override
    public List<ArticleReply> selectByArticleId(Long articleId) {
        if(articleId == null || articleId <= 0){
            log.warn(ResultCode.FAILED_PARAMS_VALIDATE.toString());
            throw  new ApplicationException(Result.failed(ResultCode.FAILED_PARAMS_VALIDATE));

        }
        List<ArticleReply> result = articleReplyMapper.selectByArticleId(articleId);
        return result;
    }
}
